package com.yf.zzmusic.utils;

import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;

import java.io.File;
import java.io.IOException;
import java.net.*;

/**
 * 获取音乐时长
 */
public class GetMusicTimer {
  /**
   * 77      * 得到文件格式
   * 78      * @param path
   * 79      * @return
   * 80
   */
  public static String getVideoFormat(String path) {
    return path.toLowerCase().substring(path.toLowerCase().lastIndexOf(".") + 1);
  }

  /**
   * 29      * 得到语音或视频文件时长,单位秒
   * 30      * @param filePath
   * 31      * @return
   * 32      * @throws IOException
   * 33
   */
  public static Float getMp3Duration(String filePath) {
    try {
      File mp3File = new File(filePath);
      MP3File f = (MP3File) AudioFileIO.read(mp3File);
      MP3AudioHeader audioHeader = (MP3AudioHeader) f.getAudioHeader();
      return Float.parseFloat(audioHeader.getTrackLength() + "");
    } catch (Exception e) {
      e.printStackTrace();
      return 0f;
    }
  }

  public static String getFileByUrl(String url) throws UnknownHostException, IOException {
    File tmpFile = File.createTempFile("temp", url.substring(url.lastIndexOf(".")));//创建临时文件
    Image2Binary.toBDFile(url, tmpFile.getCanonicalPath());
    return tmpFile.getCanonicalPath();
  }

  public static long getDuration(String filePath) throws IOException {
    long result = 0;
    result = getMp3Duration(filePath).intValue();
    return result;
  }


}
